/**
 *       Copyright (c) 2012 Lukas Zaruba
 *
 *   This file is part of Robot Playground.
 *
 *   Robot Playground is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   Robot Playground is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with Robot Playground. If not, see <http://www.gnu.org/licenses/>.
 */
package net.zarubsys.robotplayground.gui.session.wizard;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;

import net.zarubsys.commons.utils.StringUtils;
import net.zarubsys.robotplayground.core.session.Session;

import org.apache.log4j.Logger;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.WizardNewFileCreationPage;
import org.eclipse.ui.ide.IDE;

/**
 * NewSetupWizard
 *
 * @author Lukas Zaruba, lukas.zaruba@gmail.com
 */
public class NewSessionWizard extends Wizard implements INewWizard {
	
	private static final Logger LOG = Logger.getLogger(NewSessionWizard.class);

	private WizardNewFileCreationPage fileSelectionPage;
	private NewSessionGeneralPage namePage;

	public NewSessionWizard() {
		super();
		setNeedsProgressMonitor(true);
		setWindowTitle("New Setup");
	}

	@Override
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		fileSelectionPage = new WizardNewFileCreationPage("fileSelect", selection);
		fileSelectionPage.setTitle("Select destination");
		fileSelectionPage.setDescription("Select destination where result of measuring will be saved.");
		fileSelectionPage.setFileExtension("session");
		addPage(fileSelectionPage);
		
		namePage = new NewSessionGeneralPage("Name page");
		namePage.setTitle("Set name and description");
		namePage.setDescription("Set name and description of this setup.");
		addPage(namePage);
	}

	@Override
	public boolean performFinish() {
		final IFile file = fileSelectionPage.createNewFile();
		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					monitor.beginTask("Saving new setup...", -1);
					doFinish(file);
				} finally {
					monitor.done();
				}
			}
		};
		
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		
		try {
			IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file);
		} catch (PartInitException e) {
			LOG.error("Error while openning newly created resource " + file + "!", e);
			// no reaction
		}
		return true;
	}
	
	private void doFinish(IFile file) {
		Session session = new Session();
		session.setName(namePage.getFilledName());
		session.setDescription(StringUtils.getNullIfEmpty(namePage.getFilledDescription()));
		
		try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file.getRawLocation().toFile()))) {
			os.writeObject(session);
		} catch (FileNotFoundException e) {
			LOG.error("Error creating output of new Lpt measuring wizard.", e);
			throw new RuntimeException("Error creating output of new Lpt measuring wizard.");
		} catch (IOException e) {
			LOG.error("Error creating output of new Lpt measuring wizard.", e);
			throw new RuntimeException("Error creating output of new Lpt measuring wizard.");
		}
	}

}

